package ca.uwo.android.rss.events;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

  public static final String TABLE_FEEDS    = "feeds";
  public static final String TABLE_ENTRIES  = "entries";
  
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_URL = "url";
  public static final String COLUMN_NAME = "name";
  public static final String COLUMN_LAST_UPDATE = "last_update";
  
  public static final String COLUMN_FEED_ID = "feed_id";
  public static final String COLUMN_TITLE = "title";
  public static final String COLUMN_DESCRIPTION = "description";
  public static final String COLUMN_LINK = "link";
  public static final String COLUMN_DATE = "date";

  private static final String DATABASE_NAME = "database.db";
  private static final int DATABASE_VERSION = 1;

  // Database creation sql statement
  private static final String CREATE_FEEDS_TABLE  = 
						      "create table " 			+ TABLE_FEEDS + "("
						      + COLUMN_ID     			+  " integer primary key autoincrement, " 
						      + COLUMN_URL  			+  " text not null, "
							  + COLUMN_NAME      		+  " text not null, "
							  + COLUMN_LAST_UPDATE      +  " text not null);";
  
  private static final String CREATE_ENTRIES_TABLE  = 
						      "create table " 			+ TABLE_ENTRIES + "("
						      + COLUMN_ID     			+  " integer primary key autoincrement, "						      
						      + COLUMN_FEED_ID 			+  " integer not null, "
						      + COLUMN_TITLE  			+  " text not null, "
							  + COLUMN_DESCRIPTION      +  " text not null, "
							  + COLUMN_LINK             +  " text not null, "
  							  + COLUMN_DATE             +  " text not null,  "
  							  + "FOREIGN KEY (" + COLUMN_FEED_ID + ") REFERENCES " + TABLE_FEEDS + " (" + COLUMN_ID + ") );";

  public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    
    
  }

  @Override 
  public void onCreate(SQLiteDatabase database) { 
	// called when the database is created for the very first time
	Log.i("DATABASE POWER", "CREATES");  
    database.execSQL(CREATE_FEEDS_TABLE);
    database.execSQL(CREATE_ENTRIES_TABLE);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(MySQLiteHelper.class.getName(),
        "Upgrading database from version " + oldVersion + " to "
            + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_FEEDS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_ENTRIES);
    onCreate(db);
  }

} 